package service;

import graph.IdManager;
import graph.PropertyManager;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Vector;

import search.TwitterDataReader;
import search.TwitterRecord;
import search.TwitterSearcher;
import util.Common;

public class Service {

	List<TwitterRecord> search(String queryText,
			Comparator<? super TwitterRecord> comp, int number) {
		TwitterSearcher searcher = new TwitterSearcher(Common.indexDir());
		List<TwitterRecord> records = searcher.searchRecords(queryText);
		getFavorite(records);
		Collections.sort(records, comp);
		if (number < records.size()) {
			records = records.subList(0, number);
		}
		return records;
	}

	/**
	 * read from global sort file
	 * 
	 * @param sorter
	 * @param number
	 * @return
	 */
	List<TwitterRecord> list(Comparator<? super TwitterRecord> comparator,
			int number) {
		List<TwitterRecord> results = new Vector<TwitterRecord>();

		TwitterDataReader reader = new TwitterDataReader();
		reader.open(Common.getGlobalSortFile(comparator));
		for (int i = 0; i < number; i++) {
			if (reader.next() < 0) {
				break;
			}
			results.add(reader.getRecord());
		}
		return results;
	}

	private void getFavorite(List<TwitterRecord> records) {
		PropertyManager propertyManager = Common.getPropertyManager("favorite");
		propertyManager.getProperty(1);
		IdManager idManager = Common.getIdManager("tweets");
		for (TwitterRecord record : records) {
			int innerId = idManager.getId(record.m_id);
			record.m_favorite = (Integer) propertyManager
					.getProperty(new Integer(innerId));
		}
	}

	public static void main(String args[]) {
		int argIndex = 0;
		String option = args[argIndex++];
		int number = 100;
		Comparator<TwitterRecord> comp = new TwitterRecord.FavoriteCompator();
		Service service = new Service();
		List<TwitterRecord> records = new Vector<TwitterRecord>();
		if (option.equals("--search")) {
			String queryText = args[argIndex++];
			records = service.search(queryText, comp, number);
		} else if (option.equals("--list")) {
			records = service.list(comp, number);
		}
		try {
			PrintWriter writer = new PrintWriter(new FileWriter(
					Common.serviceOutputFile));
			for (TwitterRecord record : records) {
				writer.print(record);
			}
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
